package com.zjp.crud.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zjp.crud.bean.Employee;
import com.zjp.crud.bean.Msg;
import com.zjp.crud.service.EmployeeService;
import org.junit.Test;
import org.omg.PortableInterceptor.INACTIVE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理员工的CRUD
 */
@Controller
public class EmployeeController {
    @Autowired
    EmployeeService employeeService;

    //删除员工
    @ResponseBody
    @DeleteMapping("/emp/{ids}")
    public Msg deleteEmp(@PathVariable("ids") String ids){
        if (ids.contains("-")){//批量删除
            List<Integer> del_ids = new ArrayList<Integer>();
            String[] str_ids = ids.split("-");
            //组装id的集合
            for (String id : str_ids) {
                del_ids.add(Integer.parseInt(id));
            }
            employeeService.deleteBatch(del_ids);
            return Msg.success();
        }else {//单个删除
            Integer id = Integer.parseInt(ids);
            employeeService.deleteEmp(id);
            return Msg.success();
        }
    }
    //更新员工
    @ResponseBody
    @PutMapping("/emp/{empId}")
    public Msg updateEmp(Employee employee){
        employeeService.updateEmp(employee);

        return Msg.success();
    }

    //根据id查询员工
    @ResponseBody
    @GetMapping("/emp/{id}")
    public Msg getEmp(@PathVariable("id") Integer id){
        Employee employee = employeeService.getEmp(id);
        return Msg.success().add("emp", employee);
    }

    //检查用户名是否可用
    @RequestMapping("/checkuser")
    @ResponseBody
    public Msg checkuser(@RequestParam("empName") String empName){
        //先判断用户名是否是合法的表达式
        String regx = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})";
        if (!empName.matches(regx)){
            return Msg.fail().add("va_msg","用户名必须是2-5位中文或者6-16位英文和数字的组合");
        }
        //用户名合法才进行数据库用户名重复校验
        boolean b = employeeService.checkUser(empName);
        if (b){
            return Msg.success();
        }
        return Msg.fail().add("va_msg", "用户名不可用");
    }

    //保存员工
    @PostMapping("/emp")//post请求，保存员工
    @ResponseBody
    public Msg saveEmp(@Valid Employee employee, BindingResult result){//校验
        if (result.hasErrors()){
            //校验失败，返回失败，在前端横态框中显示失败信息
            Map<String, Object> map = new HashMap<String, Object>();

            List<FieldError> errors = result.getFieldErrors();
            for (FieldError error : errors) {
                System.out.println("错误的字段名：" + error.getField());
                System.out.println("错误信息：" + error.getDefaultMessage());
                map.put(error.getField(), error.getDefaultMessage());
            }
            return Msg.fail().add("errorFields", map);
        }
        employeeService.saveEmp(employee);
        return Msg.success();
    }

    /**
     * 查询所有员工
     * @param pn
     * @return
     */
    @ResponseBody//向页面返回json字符串
    @RequestMapping("/emps")
    public Msg getEmpsWithJson(@RequestParam(value = "pn", defaultValue = "1") Integer pn){
        PageHelper.startPage(pn, 5);//查询前：分页查询；当前页，每页大小

        List<Employee> emps = employeeService.getAll();//查询

        PageInfo pageInfo = new PageInfo(emps, 5);//查完后使用pageInfo包装，包含分页的详细信息

        return Msg.success().add("pageInfo", pageInfo);//返回成功，并且携带了pageInfo对象
    }
//    @RequestMapping("/emps")
    public String getEmps(@RequestParam(value = "pn", defaultValue = "1") Integer pn,
                          Model model){
        PageHelper.startPage(pn, 5);//查询前：分页查询

        List<Employee> emps = employeeService.getAll();//查询

        PageInfo pageInfo = new PageInfo(emps, 5);//查完后使用pageInfo包装，包含分页的详细信息

        model.addAttribute("pageInfo", pageInfo);//通过model传回数据给前端
        return "list";//返回list展示页面
    }
}
